from django.contrib import admin
# from .models import VehicleRecord, Bill
from .models import VehicleRecord
from django.utils.html import format_html
import time
from django.conf import settings
from django.urls import reverse

#------------------------------------------
# from .models import EntryReport, ExitReport, LogisticsInquiry, KeyDelivery, KeyDuplication, VehicleRepair
from .models import Vehicle, WarehouseEntry, WarehouseExit, LogisticsInquiry, KeyDelivery, KeyDuplication, VehicleRepair, Garage, VehicleManagement

class VehicleRecordAdmin(admin.ModelAdmin):    
    list_display = ('id', 'license_plate_link', 'entry_time', 'exit_time', 'total_duration', 'fee', 'qr_code_display', 'payment_status_display', 'display_image')
    readonly_fields = ( 'total_duration', 'fee', 'payment_status', 'payment_link','display_image', 'display_video')

    # 25 items per page
    list_per_page = 25

    fieldsets = [
        ("必填内容", {"fields": ['license_plate', 'entry_time', 'exit_time']}),
        ("可选信息", {"fields": ['image', 'video'], "classes": ['collapse']}),
        ("支付信息", {"fields": ['total_duration', 'fee', 'payment_link', 'payment_status']}),
        ("附加信息", {"fields": ['display_image', 'display_video'], "classes": ['collapse']}),
    ]

    # add some filters
    list_filter = ('entry_time', 'exit_time', 'payment_status')

    def payment_status_display(self, obj):
        if obj.payment_status == 'pending':
            color = '#DC143C' #red
            status = '待支付'
        elif obj.payment_status == 'paid':
            color = '#2ECC40' #green
            status = '已支付'
        else:
            color = '#DDDDDD' #gray
            status = '未知状态'
        
        return format_html(
            '<span style="color: white; background-color: {}; padding: 2px 5px; border-radius: 8px;">{}</span>',
            color,
            status
        )

    payment_status_display.short_description = '支付状态'

    def license_plate_link(self, obj):
        link = reverse("admin:vr_app_vehiclerecord_change", args=[obj.id])
        return format_html('<a href="{}">{}</a>', link, obj.license_plate)
    license_plate_link.short_description = '车牌号码'


    def qr_code_display(self, obj):
        if obj.payment_link is None:
            return format_html('-')
        else:
            qr_code_url = obj.get_qr_code_url()
            return format_html(
                '<img width="50" src="{}" onclick="showQRModal(\'{}\', \'{}\', \'{}\', \'{}\')" style="cursor: pointer;" />',
                qr_code_url,  # 假设每个对象都有一个qr_code_url属性
                obj.license_plate,
                obj.entry_time.strftime("%Y-%m-%d %H:%M:%S"),
                    obj.exit_time.strftime("%Y-%m-%d %H:%M:%S") if obj.exit_time != None else '-',
                qr_code_url  # 二维码图片的URL
            )

    qr_code_display.short_description = '支付二维码'
    qr_code_display.allow_tags = True  # Django 2.x之前的版本需要这个来允许HTML


    def display_image(self, obj):
        # if obj.image.url:
        #     return format_html('<img src="{}" width="100" height="auto" />', obj.image.url)
        # else:
        #     return format_html('<img src="https://placehold.co/120x70" />')
        #     # return format_html('-')
    
        if obj.image and hasattr(obj.image, 'url'):  # 检查obj.image是否存在且有url属性
            return format_html('<img src="{}" width="90" height="auto" />', obj.image.url)
        else:
            # 这里可以返回一个默认图像的URL或者一个占位符
            return format_html('-')

    display_image.short_description = '图像预览'


    def display_video(self, obj):
        if obj.video and hasattr(obj.video, 'url'):
            # 使用HTML的<video>标签来显示视频
            return format_html('<video width="320" height="240" controls><source src="{}" type="video/mp4">您的浏览器不支持视频标签。</video>', obj.video.url)
        else:
            return format_html('-')
    display_video.short_description = '视频预览'

    # kzeng add keyboard for vehicle plate, project level static files
    class Media:
        js = ('kzeng/kb.js',)


admin.site.register(VehicleRecord, VehicleRecordAdmin)


# new requirement----------------------------------------------------------------------------------------------------

# from .models import Garage, Vehicle, EntryReport, ExitReport, LogisticsInquiry, KeyDelivery, KeyDuplication, VehicleRepair, VehicleManagement

# @admin.register(Garage)
# class GarageAdmin(admin.ModelAdmin):
#     list_display = ('name', 'province', 'address')
#     search_fields = ('name', 'province', 'address')

# @admin.register(Vehicle)
# class VehicleAdmin(admin.ModelAdmin):
#     list_display = ('license_plate', 'chassis_number', 'model', 'vehicle_type', 'has_key', 'has_license')
#     search_fields = ('license_plate', 'chassis_number', 'model')
#     list_filter = ('vehicle_type',)

# @admin.register(EntryReport)
# class EntryReportAdmin(admin.ModelAdmin):
#     list_display = ('garage', 'vehicle', 'deliverer', 'deliverer_phone', 'delivery_time')
#     search_fields = ('garage__name', 'vehicle__license_plate', 'deliverer')
#     list_filter = ('garage', 'delivery_time')

# @admin.register(ExitReport)
# class ExitReportAdmin(admin.ModelAdmin):
#     list_display = ('client_name', 'vehicle', 'vehicle_items', 'parking_fee', 'pickup_person', 'pickup_time')
#     search_fields = ('client_name', 'vehicle__license_plate', 'pickup_person')
#     list_filter = ('parking_fee', 'vehicle_items', 'pickup_time')

# @admin.register(LogisticsInquiry)
# class LogisticsInquiryAdmin(admin.ModelAdmin):
#     list_display = ('client_name', 'vehicle', 'is_drivable', 'origin', 'destination')
#     search_fields = ('client_name', 'vehicle__license_plate', 'origin', 'destination')
#     list_filter = ('is_drivable',)

# @admin.register(KeyDelivery)
# class KeyDeliveryAdmin(admin.ModelAdmin):
#     list_display = ('client_name', 'vehicle', 'logistics_number', 'return_items')
#     search_fields = ('client_name', 'vehicle__license_plate', 'logistics_number')
#     list_filter = ('return_items',)

# @admin.register(KeyDuplication)
# class KeyDuplicationAdmin(admin.ModelAdmin):
#     list_display = ('client_name', 'vehicle', 'payment_by', 'return_items')
#     search_fields = ('client_name', 'vehicle__license_plate')
#     list_filter = ('payment_by', 'return_items')

# @admin.register(VehicleRepair)
# class VehicleRepairAdmin(admin.ModelAdmin):
#     list_display = ('client_name', 'vehicle', 'repair_details', 'payment_by')
#     search_fields = ('client_name', 'vehicle__license_plate', 'repair_details')
#     list_filter = ('payment_by',)

# @admin.register(VehicleManagement)
# class VehicleManagementAdmin(admin.ModelAdmin):
#     list_display = ('vehicle', 'status', 'report_time')
#     search_fields = ('vehicle__license_plate',)
#     list_filter = ('status', 'report_time')





class VehicleAdmin(admin.ModelAdmin):
    list_display = ('plate_number', 'vehicle_type', 'model')
    search_fields = ('plate_number',)


class WarehouseEntryAdmin(admin.ModelAdmin):
    list_display = ('vehicle', 'garage', 'entry_time', 'display_image')
    search_fields = ('vehicle__plate_number', 'garage__address')

    def display_image(self, obj):
        if obj.photo and hasattr(obj.photo, 'url'):  # 检查obj.image是否存在且有url属性
            return format_html('<img src="{}" width="90" height="auto" />', obj.photo.url)
        else:
            # 这里可以返回一个默认图像的URL或者一个占位符
            return format_html('-')

    display_image.short_description = '图像预览'



class WarehouseExitAdmin(admin.ModelAdmin):
    list_display = ('vehicle', 'client_name', 'pickup_time')
    search_fields = ('vehicle__plate_number', 'client_name')


class VehicleAdmin(admin.ModelAdmin):
    list_display = ('plate_number', 'vehicle_type', 'model', 'get_entry_time', 'get_exit_time')
    search_fields = ('plate_number',)

    def get_entry_time(self, obj):
        last_entry = WarehouseEntry.objects.filter(vehicle=obj).order_by('-entry_time').first()
        return last_entry.entry_time if last_entry else '无入库记录'
    get_entry_time.short_description = '最近入库时间'

    def get_exit_time(self, obj):
        last_exit = WarehouseExit.objects.filter(vehicle=obj).order_by('-pickup_time').first()
        return last_exit.pickup_time if last_exit else '无出库记录'
    get_exit_time.short_description = '最近出库时间'


class VehicleManagementAdmin(admin.ModelAdmin):
    list_display = ('vehicle', 'current_status', 'last_entry_time', 'last_exit_time')
    search_fields = ('vehicle__plate_number',)


admin.site.register(Garage)
admin.site.register(Vehicle, VehicleAdmin)
admin.site.register(WarehouseEntry, WarehouseEntryAdmin)
admin.site.register(WarehouseExit, WarehouseExitAdmin)


# admin.site.register(LogisticsInquiry)
@admin.register(LogisticsInquiry)
class LogisticsInquiryAdmin(admin.ModelAdmin):
    list_display = ('client_name', 'vehicle', 'can_drive', 'origin', 'destination')
    search_fields = ('client_name', 'vehicle__license_plate', 'origin', 'destination')
    list_filter = ('can_drive',)


@admin.register(KeyDelivery)
class KeyDeliveryAdmin(admin.ModelAdmin):
    list_display = ('client_name',  'logistics_number')
    search_fields = ('client_name', 'logistics_number')
    # list_filter = ('logistics_number',)


# admin.site.register(KeyDuplication)
@admin.register(KeyDuplication)
class KeyDuplicationAdmin(admin.ModelAdmin):
    list_display = ('client_name', 'vehicle', 'payment_by', 'return_item', 'return_address')
    search_fields = ('client_name', 'vehicle__license_plate',  'vehicle', 'notes', 'return_address')
    # list_filter = ('payment_by', 'return_items')


# admin.site.register(VehicleRepair)
@admin.register(VehicleRepair)
class VehicleRepairAdmin(admin.ModelAdmin):
    list_display = ('client_name', 'vehicle', 'payment_by')
    search_fields = ('client_name', 'vehicle', 'payment_by', 'repair_description')
    list_filter = ('payment_by',)



admin.site.register(VehicleManagement, VehicleManagementAdmin)

admin.site.site_header = "车辆出入管理系统"
admin.site.site_title  = "车辆出入管理系统"
admin.site.index_title = "欢迎使用车辆出入管理系统"